package edu.whu.xterm.activity;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.LoginFilter.UsernameFilterGeneric;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import edu.whu.xterm.R;
import edu.whu.xterm.XApplication;
import edu.whu.xterm.http.RequestBuilder;
import edu.whu.xterm.util.SharedPrefManager;

public class LoginActivity extends Activity implements View.OnClickListener,
		CompoundButton.OnCheckedChangeListener {

	static final String INVALID_PWD = "密码错误";
	static final String KICK_MULTI = "kick_multi";
	static final String HEAD_LOCATION = "Location";

	private static final int DIALOG_RETRY = 0x01;

	private static final int DIALOG_LOADING = 0x02;

	SharedPrefManager sPrefManager;

	private Button login;
	private Button navigator;
	private EditText usr;
	private EditText pwd;
	private CheckBox rememberAccount;
	private CheckBox autoLogin;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		login = (Button) findViewById(R.id.login_btn);
		navigator = (Button) findViewById(R.id.navigator_btn);

		usr = (EditText) findViewById(R.id.login_userid);
		usr.setFilters(new InputFilter[] { new UsernameFilterGeneric() });

		pwd = (EditText) findViewById(R.id.login_password);

		rememberAccount = (CheckBox) findViewById(R.id.remember_account);
		rememberAccount.setOnCheckedChangeListener(this);
		autoLogin = (CheckBox) findViewById(R.id.autologin);

		TextWatcher textWatcher = new TextChangedWatcher();
		usr.addTextChangedListener(textWatcher);
		pwd.addTextChangedListener(textWatcher);

		login.setOnClickListener(this);
		navigator.setOnClickListener(this);
		sPrefManager = ((XApplication) getApplication()).getSharedPrefManager();
		if (sPrefManager.readBoolean(SharedPrefManager.AUTO_LOGIN)) {
			final String user = sPrefManager.readString(SharedPrefManager.USER_NAME);
			final String password = sPrefManager.readString(SharedPrefManager.PASSWORD);
			if (user != null && password != null) {
				RequestBuilder builder = RequestBuilder.getBuilder();
				builder.setAuth(user, password);
				findViewById(R.id.login_form).setVisibility(View.GONE);
				new LoginAsyncTask().execute(builder);
			}
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
		login.setEnabled(usr.length() > 0 && pwd.length() > 0);

	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
		case DIALOG_LOADING: {
			return ProgressDialog.show(this, null, getString(R.string.progress_txt_sending));
		}
		default:
			break;
		}
		return super.onCreateDialog(id, args);
	}

	@Override
	public void onClick(View v) {
		if (login.equals(v)) {
			final String user = usr.getText().toString();
			final String password = pwd.getText().toString();
			RequestBuilder builder = RequestBuilder.getBuilder();
			builder.setAuth(user, password);
			new LoginAsyncTask().execute(builder);
			if (rememberAccount.isChecked()) {
				sPrefManager.writePref(SharedPrefManager.REMEMBER_USER, true);
				sPrefManager.writePref(SharedPrefManager.USER_NAME, user);
				sPrefManager.writePref(SharedPrefManager.PASSWORD, password);
			}
			sPrefManager.writePref(SharedPrefManager.AUTO_LOGIN, autoLogin.isChecked());
		} else if (navigator.equals(v)) {
			startActivity(new Intent(getApplicationContext(), MainTabActivity.class));
			finish();
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		rememberAccount.setChecked(true);
	}

	void toast(final int resId) {
		Toast.makeText(getApplicationContext(), resId, Toast.LENGTH_SHORT).show();

	}

	class TextChangedWatcher implements TextWatcher {
		private boolean pwdHasText;
		private boolean usrHasText;
		private Editable usrEdit;
		private Editable pwdEdit;

		public TextChangedWatcher() {
		}

		@Override
		public void afterTextChanged(Editable s) {
			usrEdit = usr.getText();
			pwdEdit = pwd.getText();
			if (s.length() > 0) {
				if (s.equals(usrEdit)) {
					usrHasText = true;
					if (pwdEdit.length() > 0) {
						pwdHasText = true;
					}
				} else {
					pwdHasText = true;
					if (usrEdit.length() > 0) {
						usrHasText = true;
					}
				}
			} else {
				if (s.equals(usrEdit)) {
					usrHasText = false;
				} else if (s.equals(pwdEdit)) {
					pwdHasText = false;
				}
			}
			login.setEnabled(usrHasText && pwdHasText);
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}
	}

	public class LoginAsyncTask extends AsyncTask<RequestBuilder, Void, Boolean> {

		private static final String TAG = "LoginAsyncTask";

		@Override
		protected void onPreExecute() {
			LoginActivity.this.getWindow().getDecorView().setEnabled(false);
			if (findViewById(R.id.login_form).getVisibility() == View.VISIBLE) {
				showDialog(DIALOG_LOADING);
			}
		}

		@Override
		protected Boolean doInBackground(RequestBuilder... params) {
			RequestBuilder login = params[0];
			HttpResponse response = null;
			try {
				response = login.loginRequest().call();
			} catch (Exception e) {
				Log.e(TAG, "", e);
				return false;
			}

			return handleResponse(login, response);
		}

		private boolean handleResponse(final RequestBuilder login, HttpResponse response) {
			final StatusLine statusLine = response.getStatusLine();
			if (statusLine == null) {
				return false;
			}
			switch (statusLine.getStatusCode()) {
			case HttpStatus.SC_OK: {
				HttpEntity entity = response.getEntity();
				String str;
				try {
					str = EntityUtils.toString(entity, "GB2312");
					if (str.indexOf(KICK_MULTI) > 0) {
						return handleResponse(login, login.kickMultiRequest().call());
					}
					if (str.indexOf(INVALID_PWD) > 0) {

					}
				} catch (Exception e) {
					Log.e(TAG, "", e);
					return false;
				}
				return false;
			}
			case HttpStatus.SC_MOVED_TEMPORARILY: {
				Header[] location = response.getHeaders(HEAD_LOCATION);
				if (location == null || location.length == 0) {
					return false;
				}
				((XApplication) getApplication()).setLogined(true);
				startActivity(new Intent(getApplicationContext(), MainTabActivity.class));
				finish();
				return true;
			}
			default:
				return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (findViewById(R.id.login_form).getVisibility() == View.VISIBLE) {
				dismissDialog(DIALOG_LOADING);
			}
			if (!result) {
				toast(R.string.toast_login_failed);
			}
		}
	}

}
